package com.example.myproject.easyexcel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.*;

/**
 * easyexcel 写入多个sheet文件呢
 */
public class EasyExcelMultiSheet {

    public static void main(String[] args) {
        ExcelWriter excelWriter = null;
        String fileName = "实时离寝情况报表";
        List<Map<String,Object>> list = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        map.put("dorm","123");
        map.put("stuName","456");
        list.add(map);
        map.put("dorm","33");
        map.put("stuName","333");
        list.add(map);

        try {
            FileOutputStream fos  =   new FileOutputStream("d:/3243.xls");
            // 去调用写入,这里我调用了五次，实际使用时根据数据库分页的总的页数来。这里最终会写到5个sheet里面
            excelWriter = EasyExcel.write(fos).build();
            for (int i = 0; i < 5; i++) {
                String[] header = null;
                if(i%2 ==0){
                    header = new String[]{"宿舍","姓名"};
                }else{
                    header = new String[]{"宿舍1","姓名1"};
                }
                // 每次都要创建writeSheet 这里注意必须指定sheetNo 而且sheetName必须不一样。这里注意DemoData.class 可以每次都变，我这里为了方便 所以用的同一个class 实际上可以一直变
                WriteSheet writeSheet = EasyExcel.writerSheet(i, "模板" + i).head(head(header,"3434")).build();
                // 分页去数据库查询数据 这里可以去数据库查询每一页的数据
                excelWriter.write(detail(list), writeSheet);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 千万别忘记finish 会帮忙关闭流
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }

    }

    /**动态头传入*/
    public static List<List<String>> head(String[] header, String bigTitle) {
        List<String> head0 = null;
        List<List<String>> list = new LinkedList<List<String>>();
        for (String h : header) {
            head0 = new LinkedList<>();
            head0.add(bigTitle);
            head0.add(h);
            list.add(head0);
        }
        return list;
    }

    private static  List<List<Object>> detail(List<Map<String,Object>> mapList) {
        List<List<Object>> list =  new ArrayList<List<Object>>();
        for (Map<String, Object> map : mapList) {
            List<Object> objectList = new ArrayList<>();
            objectList.add(map.get("dorm"));
            objectList.add(map.get("stuName"));
            //objectList.add("789");
            list.add(objectList);
        }
        return list;
    }

}
